// const { MongoClient, ObjectId } = required('mongodb');
const config = require('../utils/config')
const bootstrap = require('../utils/bootstrap')
// const client = new MongoClient(config.mongodb.url, config.mongodb.options);
const dbName = config.mongodb.database_name;
// const db = client.db(dbName);
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
//连接数据库
mongoose.set("strictQuery", false);
mongoose.connect(config.mongodb.url, config.mongodb.options)


// 开发者用户schema
var admin_users_schema = new Schema({
    username: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        unique: true,
        required: true
    },
    nickname: {
        type: String,
        default: "无敌的开发者"
    },
    email: {
        type: String,
    },
    location: String,
    title: String,
    description: String,
    tags: [String],
    avatar: String,
    theme: String,
    // "tfa_secret": null,
    status: {
        type: String,
        default: "active"
    },
    roles: {
        type: [mongoose.ObjectId],
        ref: 'role'
    },
    token: {
        type: String
    },
    last_access: String,
    last_page: String,
    extra: Schema.Types.Mixed
})
// 用户角色schema
var role_schema = new Schema({
    name: {
        type: String,
        unique: true,
        required: true
    },
    icon: String,
    description: String,
    ip_access: [String],
    // "enforce_tfa": false,
    admin_access: {
        type: Boolean,
        required: true,
        default: false
    },
    app_access: {
        type: Boolean,
        required: true,
        default: false
    },
    users: [{ type: mongoose.ObjectId, ref: 'user' }]
})


//将stuSchema映射到一个MongoDB collection并定义这个文档的构成
var user_model = mongoose.model('user', admin_users_schema)
var role_model = mongoose.model('role', role_schema)
//向student数据库中插入数据


// 查询所有

// 监听数据库连接状态
mongoose.connection.once('open', () => {
    console.log('--------------成功连接MONGODB数据库--------------');
    user_model.insertMany(bootstrap.users, (err, docs) => {
        if (!err) {
            console.log(docs)
            docs.forEach(e=>{
                console.log(`成功初始化用户成功！用户名：${e['username']} 密码：${e['password']}`)
            })
        }
    })
    role_model.insertMany(bootstrap.roles, (err, docs) => {
        if (!err) {
            docs.forEach(e=>{
                console.log(`成功初始化管理员权限！权限名：${e['username']} 密码：${e['password']}`)
            })
        }else{
            console.log("已有管理员权限")
        }
    })

})
mongoose.connection.once('close', () => {
    console.log('--------------MONGODB数据库连接断开--------------')
})

// client.connect().then(async e => {
//     console.log('--------------成功连接MONGODB数据库--------------');
//     const username = await db.collection('admin_users').createIndex({ username: 1 }, { unique: true })
//     const phone = await db.collection('admin_users').createIndex({ phone: 1 }, { unique: true })
//     const roles_name = await db.collection('admin_roles').createIndex({ name: 1 }, { unique: true })
//     const adminuser = await db.collection('admin_users').findOne({ 'username': config.users[0]['username'] })
//     if (!adminuser) {
//         await db.collection('admin_users').insertMany(config.users)
//     }
//     console.log(`创建索引: ${username} ${phone}`);
//     // await 
// }).catch(err => {
//     console.log(`连接失败`);
//     console.log(err)
// });
// client.on('commandStarted', (event) => console.debug(event));
// client.on('commandSucceeded', (event) => console.debug(event));
// client.on('commandFailed', (event) => console.debug(event));
// // 退出的时候
// process.on('SIGINT', function () {
//     client.close()
//     process.exit(0);
// });

module.exports = {
    user_model,
    role_model
}

